﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Catering.View_Operaction;
using Catering_Rules;
using System.Data;
using Microsoft.Reporting.WebForms;
using System.Collections;

namespace Catering.Catering_Page.Kufang
{
    public partial class CostDataStatistics : System.Web.UI.Page
    {
        #region 属性
        private DataViewForReport dvfr = new DataViewForReport();
        private DateTime STARTTIME = DateTime.Parse("1949-10-1");
        private DateTime ENDTIME = DateTime.Parse("1949-10-1");
        private FromRecords frRules = new FromRecords();
        private static View_Monitor vm = new View_Monitor();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txt_StratDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy'})");
                txt_EndDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy'})");
                loadPage();
            }
        }

        /// <summary>
        /// 绑定页面数据
        /// </summary>
        private void loadPage()
        {
            string userid = Session["PersonnelID"].ToString();
            int companyid = 0;
            int groupid = 0;
            int classid = 0;
            bool isAdmin = false;
            Bind_Data_to_Controls.GetCompanyByCurrentUser(userid, out companyid, out groupid, out classid, out isAdmin);
            Bind_Data_to_Controls.Bind_Area_ddl(ddl_OArea, isAdmin, groupid, companyid, false, false);
            AddCheckBox();

            //绑定NumericUpDown的Year
            List<string> listyears = frRules.GetYears();
            string startYear = "";
            if (listyears == null || listyears.Count <= 0)
            {
                return;
            }
            for (int i = 0; i < listyears.Count; i++)
            {
                startYear += string.Format("{0};", listyears[i]);
            }
            //txt_StratDate_NumericUpDownExtender.RefValues = startYear;
            //txt_EndDate_NumericUpDownExtender.RefValues = startYear;
            string MM = "";
            for (int ii = 1; ii <= 12; ii++)
            {
                MM += string.Format("{0};", ii);
            }
            //txt_StratDate_MM_NumericUpDownExtender.RefValues = MM;
            //txt_EndDate_MM_NumericUpDownExtender.RefValues = MM;
        }



        /// <summary>
        /// 绑定CheckBoxList
        /// </summary>
        private void AddCheckBox()
        {
            string[] str = new string[] { "金额", "采购口径（%）", "消耗口径（%）", "采购口径（元）", "消耗口径（元）", "期初库存", "期末库存", "本月采购" };
            for (int i = 0; i < str.Count(); i++)
            {
                ListItem li = new ListItem(str[i], i.ToString());
                li.Selected = true;
                CheckBoxList1.Items.Add(li);
            }
        }

        /// <summary>
        /// 获取当前勾选的类型
        /// </summary>
        /// <returns></returns>
        private ArrayList GetCheckBoxID()
        {
            ArrayList al = new ArrayList();
            foreach (ListItem item in CheckBoxList1.Items)
            {
                if (item.Selected == true)
                {
                    al.Add(item.Value);
                }
            }
            return al;
        }

        #region 各类计算
        /// <summary>
        /// 各类页面数据计算
        /// </summary>
        private string GetResult()
        {
            string result = "";
            try
            {
                //eatNumber：就餐人数（B），setNumber：配餐人数（A）
                decimal eatNumber = Convert.ToDecimal(txtEatNumbers.Text), setNumber = Convert.ToDecimal(txtSetNumbers.Text);
                //设配餐人数为A，就餐人数为B，服务比为F；如果A<B，则F=取整(A/A):取整(B/A)。
                if (GetBigValues(txtEatNumbers.Text, txtSetNumbers.Text))
                {
                    result = Toolss.GetMathResult(setNumber / setNumber, 0, 2) + "：" + Toolss.GetMathResult(eatNumber / setNumber, 0, 2);
                }
                else//否则如果A>B，则F=取整(A/B):取整(B/B)。
                {
                    result = Toolss.GetMathResult(setNumber / eatNumber, 0, 2) + "：" + Toolss.GetMathResult(eatNumber / eatNumber, 0, 2);
                }
            }
            catch { }
            return result;
        }

        private string GetSpecialRate()
        {
            string StrWhere = " SpecialRate>0 AND (ClassID=48 OR ClassID=2 OR ClassID=30 OR ClassID=4) ";
            if (!string.IsNullOrEmpty(ddl_OArea.SelectedItem.Value) && ddl_OArea.SelectedItem.Value != "-10")
            {
                StrWhere += " AND GroupID=" + ddl_OArea.SelectedItem.Value + " ";
            }
            DataTable dt = new Catering_Rules.Dynamics().GetList(StrWhere).Tables[0];
            var a = from o in dt.AsEnumerable().ToArray() select new { jine = o.Field<decimal>("SpecialRate"), renshu = o.Field<int>("Eat") };
            return "";
        }

        /// <summary>
        /// 比较大小，A值大于B值
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        /// <returns></returns>
        private bool GetBigValues(string A, string B)
        {
            try
            {
                bool flag = false;
                if (Convert.ToInt32(A) > Convert.ToInt32(B))
                {
                    flag = true;
                }
                return flag;
            }
            catch (Exception)
            {
                return false;
            }
        }
        //protected void txtSetNumbers_TextChanged(object sender, EventArgs e)
        //{
        //    GetResult();
        //}

        //protected void txtEatNumbers_TextChanged(object sender, EventArgs e)
        //{
        //    GetResult();
        //}
        //protected void txt_StratDate_TextChanged(object sender, EventArgs e)
        //{
        //    BindData();
        //}

        //protected void txt_EndDate_TextChanged(object sender, EventArgs e)
        //{
        //    BindData();
        //}

        //protected void txt_StratDate_MM_TextChanged(object sender, EventArgs e)
        //{
        //    BindData();
        //}

        //protected void txt_EndDate_MM_TextChanged(object sender, EventArgs e)
        //{
        //    BindData();
        //}

        #endregion

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            Label11.Text = "";
            Label12.Text = "";
            Label13.Text = "";
            Label14.Text = "";

            DateTime StartDate = DateTime.Now;
            DateTime EndDate = DateTime.Now;
            decimal caigoukouj = 0;//采购口径
            decimal xiaohaokouj = 0;//消耗口径
            decimal hetongavgrate = 0;//收入合同人均费率
            decimal specailrage = 0;//特殊费率
            decimal huoshiavgcb = 0;//伙食成本（考核标准）
            int catering = 0;      //就餐人数
            int eatnumber = 0;     //配餐人数
            int specialnumber = 0; //特殊人数            

            GetDate(out StartDate, out EndDate);//获取时间
            caigoukouj = GetProcureCount();
            xiaohaokouj = GetFromRecordsAmountMoney();
            Int32.TryParse(txtSetNumbers.Text, out catering);
            Int32.TryParse(txtEatNumbers.Text, out eatnumber);
            Int32.TryParse(txtSpecailRate.Text, out specialnumber);
            Decimal.TryParse(TextBox1.Text, out hetongavgrate);
            Decimal.TryParse(TextBox2.Text, out huoshiavgcb);
            specailrage = GetSpecailRate(specialnumber);
            lblServerRatio1.Text = GetResult();            //服务比计算            
            TextBox4.Text = specailrage.ToString();        //特殊费率
            lblAmountMoney.Text = caigoukouj.ToString() + "元"; //采购口径
            lblUsedMoney.Text = xiaohaokouj + "元";             //消耗口径
            if (catering > 0)
            {
                Label9.Text = Toolss.GetMathResult(caigoukouj / catering, 2, 3).ToString() + "元/天"; //人均伙食成本 采购口径
                Label10.Text = Toolss.GetMathResult(xiaohaokouj / catering, 2, 3).ToString() + "元/天"; //人均伙食成本 消耗口径
                Label11.Text = Toolss.GetMathResult(caigoukouj / catering, 2, 3) > huoshiavgcb ? "本月已超出指标" : "在考核指标内";
                Label12.Text = Toolss.GetMathResult(xiaohaokouj / catering, 2, 3) > huoshiavgcb ? "本月已超出指标" : "在考核指标内";
                if (hetongavgrate > 0)
                {
                    Label13.Text = Toolss.GetMathResult(caigoukouj / catering / hetongavgrate * 100, 2, 3) + "%";
                    Label14.Text = Toolss.GetMathResult(xiaohaokouj / catering / hetongavgrate * 100, 2, 3) + "%";
                }
            }
            Label1.Text = (hetongavgrate * catering + specailrage * specialnumber).ToString() + "元"; //餐费总收入

            ArrayList al = GetCheckBoxID();
            string GetPerson = TextBox1.Text;
            string pid = "0";
            if (Session["UserID"] != null) pid = Session["UserID"].ToString();
            DataTable dt = vm.GetCostData(pid, GetPerson, al, ddl_OArea.SelectedItem.Value, StartDate, EndDate, GetResordsDate(0), GetResordsDate(1));
            ReportDataSource rds = new ReportDataSource("DataSet1", dt);
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(rds);
            ReportViewer1.LocalReport.Refresh();
            ReportViewer1.Visible = true;
            this.LinkButton1.Text = "开始统计";
            this.LinkButton1.Enabled = true;
        }
        /// <summary>
        /// 根据下拉框的改变时间文本框的方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddl_Time_SelectedIndexChanged(object sender, EventArgs e)
        {
            txt_StratDate.Text = "";
            txt_EndDate.Text = "";
            switch (ddl_Time.SelectedItem.Value)
            {
                case "Year":
                    txt_StratDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy'})");
                    txt_EndDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy'})");
                    break;
                case "Month":
                    txt_StratDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM'})");
                    txt_EndDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM'})");
                    break;
            }
        }

        protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
        {

            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {
                if (CheckBoxList1.Items[i].Text.Equals("金额"))
                {
                    CheckBoxList1.Items[i].Selected = true;
                }
                if (CheckBoxList1.Items[i].Text.Equals("采购口径（%）"))
                {
                    if (CheckBoxList1.Items[i].Selected == true)
                    {
                        foreach (ListItem item in CheckBoxList1.Items)
                        {
                            if (item.Text.Equals("采购口径（元）"))
                            {
                                item.Selected = true;
                            }
                        }
                    }
                }
                if (CheckBoxList1.Items[i].Text.Equals("消耗口径（%）"))
                {
                    if (CheckBoxList1.Items[i].Selected == true)
                    {
                        foreach (ListItem item in CheckBoxList1.Items)
                        {
                            if (item.Text.Equals("消耗口径（元）"))
                            {
                                item.Selected = true;
                            }
                        }
                    }
                }
            }
        }

        protected void btn_EatAndCalculate_Click(object sender, EventArgs e)
        {
            txtEatNumbers.Text = "";        //就餐人数
            txtSetNumbers.Text = "";        //配餐人数
            txtSpecailRate.Text = "";       //特殊人数
            lblServerRatio1.Text = "";      //服务比计算
            lblLastInventory.Text = "";     //期末库存
            lblFirstInventory.Text = "";    //期初库存
            TextBox4.Text = "";             //特殊费率

            lblAmountMoney.Text = "";       //采购口径
            lblUsedMoney.Text = "";         //消耗口径
            Label9.Text = "";               //人均伙食成本 采购口径
            Label10.Text = "";              //人均伙食成本 消耗口径

            decimal caigoukouj = 0;//采购口径
            decimal xiaohaokouj = 0;//消耗口径
            int catering = 0;      //就餐人数
            int eatnumber = 0;     //配餐人数

            caigoukouj = GetProcureCount();
            xiaohaokouj = GetFromRecordsAmountMoney();
            this.GetPeiCanPersons(out eatnumber, out catering);

            txtEatNumbers.Text = eatnumber.ToString();//就餐人数
            txtSetNumbers.Text = catering.ToString();//配餐人数
            txtSpecailRate.Text = new Catering_Rules.Dynamics().GetSpecialRate(Convert.ToInt32(ddl_OArea.SelectedItem.Value)).ToString();//特殊人数
            lblServerRatio1.Text = GetResult();                              //服务比计算
            lblLastInventory.Text = GetFromResords(1).ToString() + "元";     //期末库存
            lblFirstInventory.Text = GetFromResords(0).ToString() + "元";    //期初库存
            TextBox4.Text = GetSpecailRate(0).ToString();                     //特殊费率

            lblAmountMoney.Text = caigoukouj.ToString() + "元";              //采购口径
            lblUsedMoney.Text = xiaohaokouj + "元";          //消耗口径
            Label9.Text = catering > 0 ? Toolss.GetMathResult(caigoukouj / catering, 2, 3).ToString() + "元/天" : "0"; //人均伙食成本 采购口径
            Label10.Text = catering > 0 ? Toolss.GetMathResult(xiaohaokouj / catering, 2, 3).ToString() + "元/天" : "0"; //人均伙食成本 消耗口径            
            //BindData();
        }

        /// <summary>
        /// 获取期初、期末库存
        /// </summary>
        /// <param name="type">0：期初库存，1：期末库存</param>
        /// <returns></returns>
        private decimal GetFromResords(int type)
        {
            DateTime SearchDate = DateTime.Now;
            int GroupId = 0;
            if (string.IsNullOrEmpty(this.txt_StratDate.Text) || string.IsNullOrEmpty(this.txt_EndDate.Text) || string.IsNullOrEmpty(this.ddl_OArea.SelectedValue) || this.ddl_OArea.SelectedValue == "-10") return 0;
            SearchDate = GetResordsDate(type);
            GroupId = Convert.ToInt32(this.ddl_OArea.SelectedValue);
            return Toolss.GetMathResult(dvfr.GetFirstInCount(SearchDate, GroupId), 2, 3);
        }

        /// <summary>
        /// 获取库存日期
        /// </summary>
        /// <param name="type">0：期初库存，1：期末库存</param>
        /// <returns></returns>
        private DateTime GetResordsDate(int type)
        {
            DateTime SearchDate = DateTime.Now;
            if (this.ddl_Time.SelectedValue == "Year")
            {
                //期初则为当年的1月1号（<当年1月2号）的库存
                //期末则为当年的12月31号（<次年1月1号）的库存
                SearchDate = new DateTime(Convert.ToInt32(this.txt_EndDate.Text), 12, 31);
                if (type == 0) SearchDate = new DateTime(Convert.ToInt32(this.txt_StratDate.Text), 1, 1);
            }
            else
            {
                //期初则为前一个月的26号（<前一个月27号）的库存
                //期末则为当月的25号（<当月26号）的库存
                DateTime.TryParse(this.txt_EndDate.Text + "-25", out SearchDate);
                if (type == 0)
                {
                    DateTime.TryParse(this.txt_StratDate.Text + "-26", out SearchDate);
                    SearchDate = SearchDate.AddMonths(-1);
                }
            }
            return SearchDate;
        }

        /// <summary>
        /// 获取时间段内的特殊费率
        /// </summary>
        /// <returns></returns>
        private decimal GetSpecailRate(int EatNumber)
        {
            DateTime StartDate = DateTime.Now;
            DateTime EndDate = DateTime.Now;
            GetDate(out StartDate, out EndDate);
            string whereClause = "SpecialRate>0 AND Dates>='" + StartDate.ToShortDateString() + "' AND Dates<'" + EndDate.AddMonths(1).ToShortDateString() + "' AND GroupID=" + this.ddl_OArea.SelectedValue + " AND (ClassID=48 OR ClassID=2 OR ClassID=30 OR ClassID=4)";
            DataTable dt = new Catering_Rules.Dynamics().GetList(whereClause).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                var query = from d in dt.AsEnumerable() select new { eat = d.Field<int>("Eat"), rate = d.Field<decimal>("SpecialRate") };
                decimal sumrate = query.ToList().Sum(o => o.rate * o.eat);
                EatNumber = EatNumber > 0 ? EatNumber : query.ToList().Sum(o => o.eat);
                return Toolss.GetMathResult(sumrate / EatNumber, 2, 3);
            }
            return 0;
        }

        /// <summary>
        /// 获取采购数口径
        /// </summary>
        /// <returns></returns>
        public decimal GetProcureCount()
        {
            DateTime StartDate = DateTime.Now;
            DateTime EndDate = DateTime.Now;
            GetDate(out StartDate, out EndDate);
            return Toolss.GetMathResult(dvfr.GetProcureCount(ddl_OArea.SelectedItem.Value, StartDate, EndDate), 2, 3);
        }

        /// <summary>
        /// 获取消耗数口径
        /// </summary>
        /// <returns></returns>
        private decimal GetFromRecordsAmountMoney()
        {
            DateTime StartDate = DateTime.Now;
            DateTime EndDate = DateTime.Now;
            GetDate(out StartDate, out EndDate);
            return frRules.GetAmountMoney(ddl_OArea.SelectedItem.Value, StartDate, EndDate);
        }

        /// <summary>
        /// 获取就餐和配餐人数
        /// </summary>
        /// <param name="EatNumber"></param>
        /// <param name="Catering"></param>
        private void GetPeiCanPersons(out int EatNumber, out int Catering)
        {
            EatNumber = 0;
            Catering = 0;
            DateTime StartDate = DateTime.MinValue;
            DateTime EndDate = DateTime.MinValue;
            string AREAID = ddl_OArea.SelectedItem.Value;

            GetDate(out StartDate, out EndDate);//获取时间
            if (AREAID == "-10")
            {
                AREAID = "";
                foreach (ListItem li in ddl_OArea.Items)
                {
                    if (li.Value != "-10") AREAID += li.Value + ",";
                }
            }

            if (StartDate.Year > 1949 && EndDate.Year > 1949)
            {
                DataTable dtDynamic = new Dynamic().GetCateringAndEatNumber(AREAID.TrimEnd(','), 0, StartDate, EndDate);
                if (dtDynamic != null && dtDynamic.Rows.Count > 0)
                {
                    if (!(dtDynamic.Rows[0]["EatNumber"] is DBNull) && !string.IsNullOrEmpty(dtDynamic.Rows[0]["EatNumber"].ToString())) EatNumber = Convert.ToInt32(dtDynamic.Rows[0]["EatNumber"].ToString());
                    if (!(dtDynamic.Rows[0]["Catering"] is DBNull) && !string.IsNullOrEmpty(dtDynamic.Rows[0]["Catering"].ToString())) Catering = Convert.ToInt32(dtDynamic.Rows[0]["Catering"].ToString());
                }
            }
        }

        /// <summary>
        /// 获取日期
        /// </summary>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        private void GetDate(out DateTime StartDate, out DateTime EndDate)
        {
            StartDate = DateTime.MinValue;
            EndDate = DateTime.MinValue;
            if (string.IsNullOrEmpty(this.txt_StratDate.Text) || string.IsNullOrEmpty(this.txt_EndDate.Text)) return;
            if (this.ddl_Time.SelectedValue == "Year")
            {
                StartDate = new DateTime(Convert.ToInt32(this.txt_StratDate.Text), 1, 1);
                EndDate = new DateTime(Convert.ToInt32(this.txt_EndDate.Text), 12, 1);
            }
            else
            {
                DateTime.TryParse(this.txt_StratDate.Text + "-1", out StartDate);
                DateTime.TryParse(this.txt_EndDate.Text + "-1", out EndDate);
            }
        }

    }
}